<template>
  <div class="main">
    <div class="title">
      {{ title }}
    </div>
    <div class="content">
      <div class="list">
        <ul>
          <li v-for="(item, index) in  currentData " :key="item._id">
            <div v-if="item.answer.length <= 1">
              <span style="font-weight: bold">{{ "" + ((currentPage - 1) * dataPerPage + index + 1) + "."
                + item.content }}</span>
              <van-radio-group v-model="selected[item._id]">
                <van-radio v-for="c in item.choices" :name="c.split('.')[0]">{{ c }}</van-radio>
              </van-radio-group>
            </div>

            <div v-else>
              <span style="font-weight: bold">{{ "" + ((currentPage - 1) * dataPerPage + index + 1) + "."
                + item.content }} </span>
              <van-checkbox-group v-model="selected[item._id]" :name="item._id">
                <van-checkbox v-for="d in item.choices" :name="d.split('.')[0]" shape="square">
                  {{ d }}
                </van-checkbox>
              </van-checkbox-group>
            </div>

            <div v-if="commited" style="font-size: 15px;font-weight: bold">
              <div :class="answerColorClass(item)">
                {{ "答案: " + item.answer }}</div>
              <div v-if="item.explain" :class="answerColorClass(item)">
                {{ "解析: " + item.explain }}</div>
            </div>

            <p></p>
          </li>

          <!-- 显示分页器 -->
          <van-pagination v-model="currentPage" :total-items="qaDataLi.length" :items-per-page="dataPerPage"
            :prev-text="prevText" :next-text="nextText" :show-page-size="5" force-ellipses @change="handlePageChange" />
        </ul>
      </div>
    </div>
    <div style="width:80vw;margin:auto;">
      <van-button class="info-submit" round type="primary" @click="commit" native-type="submit">{{ commited ? "继续练题" :
        "查看答案" }}
      </van-button>
    </div>
    <p></p>
  </div>

  <van-popup v-model:show="showScore" closeable round :style="{ height: '30%', width: '55%' }">
    <div class="centered-content">
      <!-- 这里放置您要居中显示的内容 -->
      <h2 style="margin-top: 30px;">练习结果</h2>
      <h3 :style="{ color: scoreTxtColor }">{{ scoreStr1 }}</h3>
      <h4 :style="{ color: scoreTxtColor }">{{ scoreStr2 }}</h4>
    </div>
  </van-popup>
</template>
<script>
// var jstr = `
// [{"_id":"64f95b923c5ced6198da4ca9","content":"风险管理包括策划、组织、领导、协调和控制等方面的工作，其工作流程应包括(__)步骤。","answer":"ABCD","explain":"","__v":0,"choices":["A.风险辨识","B.风险分析","C.风险控制","D.风险转移","E.风险规避"]},{"_id":"64f95b923c5ced6198da4caa","content":"构成安全隐患的因素有(__)。","answer":"BCD","explain":"","__v":0,"choices":["A.致害物","B.不安全状态+起因物","C.不安全状态+不安全行为+起因物","D.不安全行为+起因物","E.起因物"]},{"_id":"64f95b923c5ced6198da4cad","content":"《公路水运工程施工企业项目负责人施工现场带班生产制度（暂行）》规定现场带班的方式是(__)。","answer":"AC","explain":"","__v":0,"choices":["A.现场巡视检查","B.现场工作例会","C.蹲点带班生产","D.现场专题讲座","E.典型经验介绍"]},{"_id":"64f95b923c5ced6198da4cab","content":"以下物体（品）中，既是起因物又是致害物的是(__)。","answer":"BCD","explain":"","__v":0,"choices":["A.架空高压裸线","B.雷击、导电物体","C.易燃物","D.—氧化碳、瓦斯和其他有毒气体","E.水泥浆"]},{"_id":"64f95b923c5ced6198da4cac","content":"公路工程施工行业的生产经营单位新进场的从业人员，必须进行(__)的三级安全培训教育。","answer":"BCD","explain":"","__v":0,"choices":["A.区域级","B.公司","C.项目经理部（或工区、工程队等）","D.作业队（或班组等）","E.国家级"]},{"_id":"64f95b923c5ced6198da4cae","content":"下列属于安全生产管理的基本原理的是(__)。","answer":"ABCD","explain":"","__v":0,"choices":["A.系统原理","B.强制原理","C.预防原理","D.人本原理","E.破窗原理"]},{"_id":"64f95b923c5ced6198da4cb2","content":"辨识危险源除了主要使用现场调查法之外，还采用以下(__)方法。","answer":"ABC","explain":"","__v":0,"choices":["A.事故树分析法","B.安全检查表法","C.危险与可操作性研究法","D.具体实践法","E.专家论证法"]},{"_id":"64f95b923c5ced6198da4cb1","content":"人的不安全行为大多是因为对安全不重视、态度不正确、技能或知识不足、健康或生理状态不佳和劳动条件不良等因素造成的。下列属于人的不安全行为的是(__)。","answer":"ABCD","explain":"","__v":0,"choices":["A.使用不安全设备","B.以手工取代工具","C.冒险进人危险场所","D.不安全装束","E.未贯彻落实安全管理法律法规"]},{"_id":"64f95b923c5ced6198da4cb0","content":"下列属于第一类危险源的是(__)。","answer":"ABCD","explain":"","__v":0,"choices":["A.吊起重物的势能","B.噪声的声能","C.机械和车辆的动能","D.高处坠落的势能","E.未正确佩戴安全防护用品"]}]
// `
// var qas = JSON.parse(jstr)
// import axios from 'axios'
import { ref, watch } from 'vue';
import { Toast } from 'vant';

export default {
  data() {
    return {
      selected: {},
      qaDataLi: [],
      title: '',
      // 分页
      currentPage: 1, // 当前页数
      prevText: '上一页',
      nextText: '下一页',
      dataPerPage: 20, // 每页显示的数据数量
      showScore: false,
      scoreStr1: '',
      scoreStr2: '',
      pass: false,
      scoreTxtColor: 'red',
      commited: false
    }
  },
  activated() {
    // 在组件创建时请求数据
    this.fetchQa();
  },
  methods: {
    async fetchQa() {
      this.qaDataLi = []
      const examIndex = localStorage.getItem('examIndex')
      if (!examIndex) {
        Toast.fail('请先选择题库');
        return
      }
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
      });
      const fetch = () => {
        console.log('Qa fetch cache')
        this.title = localStorage.getItem('examName')
        const cacheKey = 'qasCache' + examIndex
        const cache = localStorage.getItem(cacheKey)
        if (cache) {
          console.log('fetchQa 使用缓存 cacheKey', cacheKey)
          this.qaDataLi = JSON.parse(cache)
          // Toast.clear()
          Toast.success('习题总数 ' + this.qaDataLi.length)
        } else {
          setTimeout(fetch, 1500)
        }
      }
      setTimeout(fetch, 0)
    },

    commit() {
      this.commited = !this.commited
      console.log(this.commited)
      if (this.commited) {
        setTimeout(() => {
          var score = 0
          var sum = 0
          for (var i = 0; i < this.qaDataLi.length; i++) {
            var item = this.qaDataLi[i]
            if (!item.answer) {
              continue
            }
            sum++
            var correct = this.selected[item._id] && (this.selected[item._id].length > 1 ? this.selected[item._id].sort().join('') : this.selected[item._id]) === item.answer
            if (correct) {
              score++
            }
          }
          this.pass = score > sum * 0.8
          this.scoreTxtColor = this.pass ? 'green' : 'red'
          this.scoreStr1 = '你的成绩：' + score + '/' + sum
          this.scoreStr2 = (this.pass ? '恭喜你通过了' : '没有通过，请继续努力')
          this.showScore = true
        }, 0)
      }
    },

    answerColorClass(item) {
      return (this.selected[item._id] && (this.selected[item._id].length > 1 ? this.selected[item._id].sort().join('') : this.selected[item._id]) === item.answer) ? 'text-green' : 'text-red'
    },

    // passColorClass(item) {
    //   return this.pass ? 'text-green' : 'text-red'
    // },
    // 处理分页切换事件
    handlePageChange(newPage) {
      this.currentPage = newPage;
    },
  },
  computed: {
    // 根据当前页数和每页数据数量计算当前页的数据
    currentData() {
      const startIndex = (this.currentPage - 1) * this.dataPerPage;
      const endIndex = startIndex + this.dataPerPage;
      return this.qaDataLi.slice(startIndex, endIndex);
    },
  },
}

</script>
<style lang="less" scoped>
.main {
  background: #fff;
  padding: 5vw;

  .title {
    font-weight: bold;
    font-size: 16px;
    color: #0074FF;
  }

  .content {
    padding: 5vw 0;
    text-align: left;
    font-size: 16px;

    .newspaper {
      color: #666666;
      margin-bottom: 5vw;
    }

    .list {
      .list-title {
        color: #666;
        line-height: 10vw;
      }

      .van-checkbox,
      .van-radio {
        .img-icon {
          width: 5vw;
        }

        padding:1vw 0;

        .van-checkbox__label {
          color: #666 !important;
        }

      }
    }
  }

  .text-red {
    color: red;
  }

  .text-green {
    color: green;
  }

  .centered-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
    margin-top: 30px;
    padding-left: 50px;
    padding-right: 50px;
    /* 让内容占满整个弹窗高度 */
  }
}
</style>